<template>
  <div style="padding: 15px;">
    <vxe-toolbar id="warehouseLocationId" :custom="{storage: true}" export :refresh="{query: findList}">
      <template v-slot:buttons>
        <el-button @click="findList">查询</el-button>
        <el-button @click="funcAdd">新增</el-button>
        <el-button @click="start">启用</el-button>
        <el-button @click="block">停用</el-button>
        <el-button @click="upload">导入</el-button>
        <el-button @click="vessel">库位编码打印</el-button>
      </template>
    </vxe-toolbar>
    <vxe-table
      ref="xTable"
      border
      resizable
      stripe
      highlight-current-row
      show-footer
      highlight-hover-row
      row-id="id"
      align="center"
      class="mytable-footer"
      height="700"
      :loading="loading"
      :data="tableData"
      :edit-config="{trigger: 'click', mode: 'row', showStatus: true}"
      sort-config.remote
      @sort-change="sortList"
      :export-config='{type:"csv"}'
      :seq-config="{startIndex: listQuery.pageNum * listQuery.pageSize - listQuery.pageSize}"
    >
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <vxe-table-column type="checkbox" width="60"></vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="status" title="状态" min-width="150" sortable show-header-overflow show-overflow
                          :formatter="formatterStatus"/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.status" placeholder="请选择状态" clearable>
            <el-option value="0" label="启用"/>
            <el-option value="1" label="停用"/>
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="warehouseName" title="所属仓库" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.warehouseCode" placeholder="请输入所属仓库 " style="width:100%" clearable>
            <el-option
              v-for="item in warehouseData"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="spaceName" title="所属库区" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.spaceCode" placeholder="请输入所属库区 " style="width:100%" clearable>
            <el-option
              v-for="item in spaceData"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="serialNumber" title="库位编码" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.serialNumber" placeholder="请输入库位编码" clearable/>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="locationType" title="库位类型" min-width="150" sortable :formatter="formatterLocation"/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.locationType" placeholder="请输入库位类型 " style="width:100%" clearable>
            <el-option
              v-for="item in locationTypeData"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="bearTypeName" title="库位承载类型" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.bearType" placeholder="请输入库位承载类型 " style="width:100%" clearable>
            <el-option
              v-for="item in bearTypeData"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="shelvesNumber" title="上架动线号" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.shelvesNumber" placeholder="请输入上架动线号" clearable/>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="pickNumber" title="拣货动线号" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.pickNumber" placeholder="请输入拣货动线号" clearable/>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="inventoryNumber" title="盘点动线号" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.inventoryNumber" placeholder="请输入盘点动线号" clearable/>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="storageStrategy" title="混放策略" min-width="150" sortable
                          :formatter="formatterStorageStrategy"/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.storageStrategy" placeholder="请输入混放策略 " style="width:100%" clearable>
            <el-option
              v-for="item in storageStrategyTypeData"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="ioLock" title="出入库锁" min-width="150" sortable :formatter="formatterIoLock"/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.ioLock" placeholder="请输入出入库锁 " style="width:100%" clearable>
            <el-option
              v-for="item in ioLockData"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>

        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="createdName" title="创建人" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.createdName" placeholder="请输入创建人" clearable/>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="gmtCreated"
          show-header-overflow
          show-overflow
          title="创建时间"
          min-width="420"
          sortable
          :resizable="false"
        />
        <template v-slot:header>
          <el-date-picker
            v-model="gmtCreatedRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"

            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'gmtCreated')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="modifiedName" title="修改人" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.modifiedName" placeholder="请输入修改人" clearable/>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="gmtModified"
          show-header-overflow
          show-overflow
          title="修改时间"
          min-width="420"
          sortable
          :resizable="false"
        />
        <template v-slot:header>
          <el-date-picker
            v-model="gmtModifiedRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"

            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'gmtModified')"
          />
        </template>
      </vxe-table-column>

      <!-- <vxe-table-column>
        <vxe-table-column field="warehouseCode" :formatter="formatterStatus" title="所属仓库" min-width="150" sortable />
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.warehouseCode" placeholder="请选择所属仓库" @change="findwarehouseSpaceList" style="width: 100%">
            <el-option v-for="item in warehouseList" :key="item.code" :label="item.name" :value="item.code" />
          </el-select>
        </template>
      </vxe-table-column> -->
      <vxe-table-column title="操作" fixed="right" min-width="150">
        <template slot-scope="scope">
          <el-tooltip  effect="dark" content="详情" placement="top">
            <vxe-button type="text" @click="funcDetail(scope.row.code)">
              <i class="el-icon-document"/>
            </vxe-button>
          </el-tooltip>
          <el-tooltip  effect="dark" content="编辑" placement="top">
            <vxe-button type="text" @click="funcEdit(scope.row.code)">
              <i class="el-icon-edit"/>
            </vxe-button>
          </el-tooltip>
          <el-tooltip  effect="dark" content="删除" placement="top">
            <vxe-button type="text" @click="funcDelete(scope.row.code)">
              <i class="el-icon-delete"/>
            </vxe-button>
          </el-tooltip>

        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager
      :loading="loading"
      :current-page.sync="listQuery.pageNum"
      :page-size.sync="listQuery.pageSize"
      :total="listQuery.total"
      :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
      @page-change="handlePageChange"
    />

    <vxe-modal v-model="vesselShow" title="打印库位编码" destroy-on-close resize :show-zoom="false">
      <barCode :vesselList="vesselList" />
    </vxe-modal>

    <vxe-modal v-model="modelAddFlag" title="新增" width="700" height="550" destroy-on-close resize>
      <compAdd ref="addRef" @fatherAddMethod="fatherAdd" @fatherCancelMethod="fatherCancel" :warehouseData="warehouseData" :bearTypeData="bearTypeData"/>
    </vxe-modal>
    <vxe-modal v-model="modelEditFlag" title="编辑" width="700" height="550" destroy-on-close  resize>
      <compEdit ref="editRef" @fatherEditMethod="fatherEdit" @fatherCancelMethod="fatherCancel" :operationCode="operationCode" :warehouseData="warehouseData" :bearTypeData="bearTypeData"/>
    </vxe-modal>
    <vxe-modal v-model="modelDetailFlag" title="详情" width="700" height="550" destroy-on-close resize>
      <compDetail ref="detailRef" :operationCode="operationCode" :warehouseData="warehouseData" :bearTypeData="bearTypeData"/>
    </vxe-modal>
    <vxe-modal v-model="modelUploadFlag" title="导入" width="1300" height="900" destroy-on-close>
      <dataImport type="locationManage" @importFileSuccess="importFileSuccess" />
    </vxe-modal>
  </div>
</template>
<script>
  import Vue from 'vue'
  import 'xe-utils'
  import VXETable from 'vxe-table'
  import 'vxe-table/lib/index.css'
  import XEUtils from 'xe-utils'
  import VXEUtils from 'vxe-utils'
  Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ['cookie'] })
  import compAdd from './components/locationControllerAdd.vue'
  import compEdit from './components/locationControllerEdit.vue'
  import compDetail from './components/locationControllerDetail.vue'
  import dataImport from '@/views/components/importFile'
  import barCode from '@/views/components/barCode'

  import {
    locationList,
    locationActive,
    locationUnActive,
    locationDelete,
    getWarehouse,
    getWarehouseSpace,
    getLocationBearType,
  } from '@/api/basicInfo'

  export default {
    name: 'Parent',
    components: {
      compAdd,
      compEdit,
      compDetail,
      barCode,
      dataImport
    },
    data() {
      return {
        pickerOptions: {
          shortcuts: [
            {
              text: '最近一周',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                picker.$emit('pick', [start, end])
              }
            },
            {
              text: '最近一个月',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                picker.$emit('pick', [start, end])
              }
            },
            {
              text: '最近三个月',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
                picker.$emit('pick', [start, end])
              }
            }
          ]
        },
        vesselList: [],
        message: '',
        loading: false,
        tableData: [],
        vesselShow: false,
        modelAddFlag: false,
        modelUploadFlag:false,
        modelEditFlag: false,
        modelDetailFlag: false,
        gmtCreatedRange: '',
        gmtModifiedRange: '',
        copy: false,
        warehouseData: [],           //仓库列表
        spaceData: [],               //库区列表
        locationTypeData: [          //库位类型列表
          { code: '0', name: '拣货' },
          { code: '1', name: '存货' },
          { code: '2', name: '集货' }
        ],
        bearTypeData: [],            //库位承载类型列表
        storageStrategyTypeData: [   //混放策略列表
          { code: '0', name: '商品混放' },
          { code: '1', name: '批次混放' },
          { code: '2', name: '混放' },
          { code: '3', name: '不混放' }
        ],
        ioLockData: [                //出入库锁列表
          { code: '0', name: '入库锁' },
          { code: '1', name: '出库锁' },
          { code: '2', name: '全锁' },
          { code: '3', name: '不锁' }
        ],
        listQuery: {
          bearType: '',                            //库位承载类型 ,
          code: '',                                //数据标识 ,
          inventoryNumber: '',                     //盘点动线号 ,
          ioLock: '',                              //出入库锁 ,
          locationType: '',                        //库位类型 ,
          name: '',                                //库位名称 ,
          pickNumber: '',                          //拣货动线号 ,
          remarks: '',                             //备注 ,
          serialNumber: '',                        //编码 ,
          shelvesNumber: '',                       //上架动线号 ,
          spaceCode: '',                           //所属库区 ,
          status: '',                              //状态 ,
          storageStrategy: '',                     //存放策略 ,
          warehouseCode: '',                       //所属仓库
          createdBy: '',      //创建人
          createdName: '',      //创建人
          modifiedBy: '',     //修改人
          modifiedName: '',     //修改人
          gmtCreated: '',     //创建时间
          gmtModified: '',    //修改时间
          total: 0,          //总数
          pageNum: 1,
          pageSize: 10,
          sortField: '',
          sortType: ''
        },
        operationCode:[],// 编辑、查看 接口所需id
      }
    },
    created() {
      this.getType();
      this.findList();
    },
    methods: {
      //查询仓库、库区、库位承载类型、库位
      getType() {
        getWarehouse().then(response => {
          this.warehouseData = response.data
        })
        getWarehouseSpace().then(response => {
          this.spaceData = response.data
        })
        getLocationBearType().then(response => {
          this.bearTypeData = response.data
        })
      },
      changeDate(value, prefix) {
        if (value) {
          this.listQuery[`${prefix}Start`] = value[0] + ' 00:00:00'
          this.listQuery[`${prefix}End`] = value[1] + ' 23:59:59'
        } else {
          this.listQuery[`${prefix}Start`] = ''
          this.listQuery[`${prefix}End`] = ''
        }
      },

      // 翻译库位承载类型
      formatterLocation({ cellValue }) {
        const sd = this.locationTypeData.find(i => i.code === cellValue)
        return sd ? sd.name : ''
      },

      //启用
      start() {
        let selectRecords = this.$refs.xTable.getCheckboxRecords()
        let arr = []
        selectRecords.forEach(i => {
          arr.push(i.code)
        })
        arr = arr.join(',')
        if (arr.length != 0) {
          this.$confirm('确认启用吗？').then(_ => {
            this.loading = true
            locationActive(arr).then(response => {
              this.$message({ message: response.msg, type: 'success' })
              this.findList()
              this.loading = false
            })
          })
        } else {
          this.$message('没有能启用的数据！')
        }
      },
      //停用
      block() {
        let selectRecords = this.$refs.xTable.getCheckboxRecords()
        let arr = []
        selectRecords.forEach(i => {
          arr.push(i.code)
        })
        arr = arr.join(',')
        if (arr.length != 0) {
          this.$confirm('确认停用吗？').then(_ => {
            this.loading = true
            locationUnActive(arr).then(response => {
                this.$message({ dangerouslyUseHTMLString: true,message: response.msg, type: 'success'})
              this.findList()
              this.loading = false
            })
          }).catch(_ => {
          })
        } else {
          this.$message('没有能停用的数据！')
        }
      },
      // 翻译状态
      formatterStatus({ cellValue }) {
        if (cellValue === '0') {
          return '启用'
        } else if (cellValue === '1') {
          return '停用'
        }
      },
      //翻译混放策略
      formatterStorageStrategy({ cellValue }) {
        if (cellValue === '0') {
          return '商品混放'
        }
        if (cellValue === '1') {
          return '批次混放'
        }
        if (cellValue === '2') {
          return '混放'
        }
        if (cellValue === '3') {
          return '不混放'
        }
      },
      // 翻译出入库锁
      formatterIoLock({ cellValue }) {
        if (cellValue === '0') {
          return '入库锁'
        }
        if (cellValue === '1') {
          return '出库锁'
        }
        if (cellValue === '2') {
          return '全锁'
        }
        if (cellValue === '3') {
          return '不锁'
        }
      },

      //获取列表
      findList() {
        this.loading = true
        return locationList(this.listQuery).then(response => {
          this.tableData = response.data.records
          this.listQuery.total = response.data.total
          this.loading = false
        })
      },
      // 排序
      sortList({ column, property, order }) {
        if (order) {
          this.listQuery.sortField = property
          this.listQuery.sortType = order
        } else {
          this.listQuery.sortField = ''
        }
        this.findList()
      },
      // 添加方法
      funcAdd() {
        // this.$refs.addRef.reset();    //重置
        // this.$refs.addRef.warehouseData = this.warehouseData
        // this.$refs.addRef.bearTypeData = this.bearTypeData
        this.modelAddFlag = true
      },
      // 修改方法
      funcEdit(code) {
        this.operationCode = code
        // this.$refs.editRef.getInfo(code)
        // this.$refs.editRef.warehouseData = this.warehouseData
        // this.$refs.editRef.spaceData = this.spaceData
        // this.$refs.editRef.bearTypeData = this.bearTypeData
        this.modelEditFlag = true
      },
      // 详情方法
      funcDetail(code) {
         this.operationCode = code
        // this.$refs.detailRef.getInfo(code)
        // this.$refs.detailRef.warehouseData = this.warehouseData
        // this.$refs.detailRef.spaceData = this.spaceData
        // this.$refs.detailRef.bearTypeData = this.bearTypeData
        this.modelDetailFlag = true
      },
      // 删除方法
      funcDelete(row) {
        this.$confirm('确认删除吗？').then(_ => {
          locationDelete(row).then(response => {
            this.$message({ dangerouslyUseHTMLString: true,message: response.msg, type: 'success'})
            this.findList()
          })
        }).catch(_ => {
        })
      },
      // 增加组件的父方法
      fatherAdd() {
        this.modelAddFlag = false
        this.findList()
      },
      // 编辑组件的父方法
      fatherEdit() {
        this.modelEditFlag = false
        this.findList()
      },
      // 公共取消
      fatherCancel(modelFlag) {
        switch (modelFlag) {
          case 'add':
            this.modelAddFlag = false
            break
          case 'edit':
            this.modelEditFlag = false
            break
          case 'detail':
            this.modelDetailFlag = false
            break
          case 'upload':
            this.modelUploadFlag = false
            break
          default:
        }
      },
      // 分页handle
      handlePageChange({ currentPage, pageSize }) {
        this.listQuery.pageNum = currentPage
        this.listQuery.pageSize = pageSize
        this.findList()
      },

      upload(){
        this.modelUploadFlag = true;
      },
      // 条形码
      vessel(){
        let selectRecords = this.$refs.xTable.getCheckboxRecords()
        let arr = []
        selectRecords.forEach(i => {
          arr.push(i.serialNumber)
        })
        // arr = arr.join(',')
        if (arr.length != 0) {
          this.vesselList = arr
          this.vesselShow = true
        } else {
          this.$message('请选择单据进行库位编码打印')
        }
      },
      importFileSuccess(){
        this.modelUploadFlag = false;
        this.findList();
      },
      // 底部颜色设置
      /*  footerCellClassName({ $rowIndex, column, columnIndex }) {
         if (columnIndex === 0) {
           if ($rowIndex === 0) {
             return 'col-blue'
           } else {
             return 'col-red'
           }
         }
       }, */
      // 设置底部合计
      footerMethod({ columns, data }) {
        return [
          columns.map((column, columnIndex) => {
            if (columnIndex === 0) {
              return '合计'
            }
            if (['pageviews', 'forecast'].includes(column.property)) {
              return XEUtils.sum(data, column.property)
            }
            return null
          })
        ]
      }
    }
  }
</script>

<style>
  .vxe-table .vxe-body--column:not(.col--ellipsis), .vxe-table .vxe-footer--column:not(.col--ellipsis), .vxe-table .vxe-header--column:not(.col--ellipsis) {
    padding: 6px 0;
  }

  .vxe-toolbar {
    padding: 0 0 10px 0
  }
</style>
